"use client";

import { useState, useEffect } from "react";

interface ModelStatus {
  model_loaded: boolean;
  model_type: string;
  supported_features: string[];
}

/**
 * 系统状态监控组件
 * 功能：显示后端API连接状态和模型状态
 * 使用场景：实时监控系统运行状态
 */
export default function SystemStatus() {
  const [isConnected, setIsConnected] = useState<boolean | null>(null);
  const [modelStatus, setModelStatus] = useState<ModelStatus | null>(null);
  const [lastChecked, setLastChecked] = useState<Date | null>(null);

  /**
   * 检查系统状态
   */
  const checkSystemStatus = async () => {
    try {
      // 检查健康状态
      const healthResponse = await fetch("/health");
      const isHealthy = healthResponse.ok;

      // 检查模型状态
      const modelResponse = await fetch("/api/model/status");
      const modelData = modelResponse.ok ? await modelResponse.json() : null;

      setIsConnected(isHealthy);
      setModelStatus(modelData);
      setLastChecked(new Date());
         } catch {
       setIsConnected(false);
       setModelStatus(null);
       setLastChecked(new Date());
     }
  };

  // 组件挂载时检查状态，并设置定时检查
  useEffect(() => {
    checkSystemStatus();
    
    // 每30秒检查一次状态
    const interval = setInterval(checkSystemStatus, 30000);
    
    return () => clearInterval(interval);
  }, []);

  /**
   * 获取状态指示器的样式
   */
  const getStatusStyle = () => {
    if (isConnected === null) {
      return {
        color: "text-gray-500",
        bgColor: "bg-gray-500",
        text: "检查中..."
      };
    }
    
    if (isConnected && modelStatus?.model_loaded) {
      return {
        color: "text-green-600",
        bgColor: "bg-green-500",
        text: "运行正常"
      };
    }
    
    if (isConnected && !modelStatus?.model_loaded) {
      return {
        color: "text-yellow-600",
        bgColor: "bg-yellow-500",
        text: "模型未加载"
      };
    }
    
    return {
      color: "text-red-600",
      bgColor: "bg-red-500",
      text: "连接断开"
    };
  };

  const statusStyle = getStatusStyle();

  return (
    <div className="flex items-center space-x-3">
      {/* 状态指示器 */}
      <div className="flex items-center space-x-2">
        <div className={`w-3 h-3 rounded-full ${statusStyle.bgColor} animate-pulse`}></div>
        <span className={`text-sm font-medium ${statusStyle.color}`}>
          {statusStyle.text}
        </span>
      </div>

      {/* 详细状态信息（悬停显示） */}
      <div className="relative group">
        <button
          onClick={checkSystemStatus}
          className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1 rounded transition-colors"
          title="刷新状态"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
        </button>

        {/* 状态详情提示框 */}
        <div className="absolute right-0 top-8 w-64 bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-lg shadow-lg p-4 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-10">
          <div className="space-y-3">
            <h4 className="font-semibold text-gray-900 dark:text-white">系统状态</h4>
            
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600 dark:text-gray-400">API连接：</span>
                <span className={isConnected ? "text-green-600" : "text-red-600"}>
                  {isConnected === null ? "检查中..." : isConnected ? "正常" : "断开"}
                </span>
              </div>
              
              <div className="flex justify-between">
                <span className="text-gray-600 dark:text-gray-400">模型状态：</span>
                <span className={modelStatus?.model_loaded ? "text-green-600" : "text-red-600"}>
                  {modelStatus?.model_loaded ? "已加载" : "未加载"}
                </span>
              </div>
              
              {modelStatus?.model_type && (
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">模型类型：</span>
                  <span className="text-gray-900 dark:text-white">
                    {modelStatus.model_type}
                  </span>
                </div>
              )}
              
              {lastChecked && (
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">最后检查：</span>
                  <span className="text-gray-900 dark:text-white">
                    {lastChecked.toLocaleTimeString()}
                  </span>
                </div>
              )}
            </div>

            {/* 支持的特征 */}
            {modelStatus?.supported_features && (
              <div className="border-t border-gray-200 dark:border-slate-600 pt-3">
                <p className="text-xs text-gray-600 dark:text-gray-400 mb-2">支持的特征：</p>
                <div className="flex flex-wrap gap-1">
                  {modelStatus.supported_features.map((feature) => (
                    <span
                      key={feature}
                      className="px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-xs rounded"
                    >
                      {feature}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
} 